import React, { useRef, useState, useEffect } from "react";
import { Button, Form, Input, Row, Col, message } from "antd";
import "../index.scss";
import { getCaptchaApi, userIsExistApi, addUserApi } from "@/api/user.js";
import { useDispatch } from "react-redux";
import { initUserInfo, changeLoginStatus } from "@/redux/userSlice";

/**
 * 注册表单
 */
export default function Register(props) {
  const dispatch = useDispatch();
  const registerRef = useRef();
  const [registerInfo, setRegisterInfo] = useState({
    loginId: "",
    nickname: "",
    captcha: "",
  });
  const [captcha, setCaptcha] = useState(null);

  const update = (oldInfo, newInfo, key, setRegisterInfo) => {
    const obj = { ...oldInfo };
    obj[key] = newInfo;
    setRegisterInfo(obj);
  };

  // 切换验证码
  const handleClickCaptcha = async () => {
    const res = await getCaptchaApi();
    setCaptcha(res);
  };

  useEffect(() => {
    handleClickCaptcha();
  }, [props.isModalOpen]);

  // 检查用户是否存在
  const checkUserIsExist = async () => {
    if (registerInfo.loginId) {
      const res = await userIsExistApi(registerInfo.loginId);
      if (res.data) {
        message.warning("用户名已存在");
      }
    }
  };

  const clearContent = () => {
    setRegisterInfo({ loginId: "", nickname: "", captcha: "" });
    props.onClose();
  };

  const onFinish = async (userInfo) => {
    const res = await addUserApi(userInfo);
    if (res.code !== 0) {
      // 验证失败 -> 提示 -> 刷新验证码
      message.error(res.msg);
      handleClickCaptcha();
    } else {
      // 验证通过 -> 放入数据仓库 -> 转化登录状态 -> 清除注册数据 & 关闭 Modal
      message.success("注册成功，默认密码为123456");
      dispatch(initUserInfo(res.data));
      dispatch(changeLoginStatus(true));
      clearContent();
    }
  };

  return (
    <>
      <Form
        name="basic"
        onFinish={onFinish}
        autoComplete="off"
        style={{ width: "450px", margin: "20px auto" }}
        ref={registerRef}
      >
        <Form.Item
          label="注册账号"
          name="loginId"
          rules={[
            { required: true, message: "请输入账号" },
            { min: 3, max: 10, message: "账号长度不能小于3位，不能大于10位" },
            { validator: checkUserIsExist },
          ]}
          validateTrigger="onBlur"
        >
          <Input
            placeholder="请输入账号"
            value={registerInfo.loginId}
            onChange={(e) => update(registerInfo, e.target.value, "loginId", setRegisterInfo)}
          />
        </Form.Item>

        <Form.Item
          label="用户昵称"
          name="nickname"
          rules={[{ min: 3, max: 10, message: "昵称长度不能小于3位，不能大于10位" }]}
        >
          <Input
            placeholder="请输入昵称，不填写默认为新用户xxx"
            value={registerInfo.nickname}
            onChange={(e) => update(registerInfo, e.target.value, "nickname", setRegisterInfo)}
          />
        </Form.Item>

        <Form.Item
          label="验证码："
          name="captcha"
          rules={[
            { required: true, message: "请输入验证码" },
            {
              validator: (_, value) => {
                let reg = /^[^\u4e00-\u9fa5]+$/g;
                if (!value) {
                  return Promise.resolve();
                }
                if (!reg.test(value)) {
                  return Promise.reject("只能输入数字或字母");
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Row align="middle">
            <Col span={16}>
              <Input
                placeholder="请输入验证码"
                value={registerInfo.captcha}
                onChange={(e) => update(registerInfo, e.target.value, "captcha", setRegisterInfo)}
              />
            </Col>
            <Col span={6}>
              <div
                className=""
                dangerouslySetInnerHTML={{ __html: captcha }}
                onClick={handleClickCaptcha}
              ></div>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
            注册
          </Button>
          <Button type="primary" htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </>
  );
}
